<template>
  <BasicModal @register="registerChangeModal" @ok="handleSubmit" v-bind="$attrs">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { addDicDetail, updateDicDetail } from '/@/api/system/dic';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const props = defineProps({
    dicId: String,
    title: String,
  });
  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t(props.title + '分类名称'),
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: t('请填写名称'),
      },
      colProps: { span: 24 },
    },
    {
      field: 'code',
      label: t(props.title + '分类编码'),
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: t('请填写编码'),
      },
      colProps: { span: 24 },
    },
    {
      field: 'sortCode',
      label: t('排序'),
      required: true,
      component: 'InputNumber',
      componentProps: {
        style: { width: '100%' },
        placeholder: t('请填写排序'),
      },
      colProps: { span: 24 },
    },
    {
      label: t('备注'),
      field: 'remark',
      component: 'InputTextArea',
      componentProps: {
        placeholder: t('请填写备注'),
      },
      colProps: { span: 24 },
    },
  ];
  const { notification } = useMessage();
  const editItemId = ref<string>('');

  const emits = defineEmits(['success', 'register']);
  const [registerChangeModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    editItemId.value = data.info?.id || '';
    if (data.info) {
      //编辑赋值
      setFieldsValue(data.info);
    }

    console.log('editItemId', data.info, editItemId.value);

    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      draggable: false,
      title: data.title,
      destroyOnClose: true,
      width: 450,
    });
  });
  const [registerForm, { setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    labelCol: { span: 7 },
  });

  const handleSubmit = async () => {
    const values = await validate();
    values.itemId = props.dicId;
    values.value = values.code;
    if (editItemId.value) {
      values.id = editItemId.value;
      await updateDicDetail(values);
    } else {
      await addDicDetail(values);
    }
    closeModal();
    emits('success');
    notification.success({
      message: t('提示'),
      description: `${editItemId.value ? t('修改') : t('新增')}` + t('成功'),
    });
  };
</script>
